package com.wzdigit.wms.wms.http;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wzdigit.framework.Shift;
import com.wzdigit.wms.wms.domain.dto.TmsResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
public class TmsHttpClient {
    private  final  static  String  customerId = "zs-wms";
    private  final  static  String  secretKey = "2321de7c340ee2d438a2123771af40e2";
    /**根据TMS给的接口规则组建数据
        * @param param
        * @return java.lang.String
        * @author shuaic
        * @date 2021/9/15 22:33
    */
    public  String  createSign(String param) throws UnsupportedEncodingException {
        String  dt = DateUtil.format(new Date(),"yyyy-MM-dd HH:ss:dd");
        StringBuffer sb = new StringBuffer();
        sb.append("customerId="+customerId+"&");
        sb.append("data="+param+"&");
        sb.append("secretKey="+secretKey+"&");
        sb.append("timestamp="+dt);
        // String sign = DigestUtils.md5DigestAsHex("customerId=zs-wms&data={}&secretKey=2321de7c340ee2d438a2123771af40e2&timestamp=2020-04-26 00:00:07".getBytes("UTF-8")).toUpperCase();
        String sign = DigestUtils.md5DigestAsHex(sb.toString().getBytes("UTF-8")).toUpperCase();

        Map<String,String> map = new HashMap<>();
        map.put("customerId",customerId);
        map.put("sign",sign);
        map.put("data",param);
        map.put("timestamp",dt);

        return JSON.toJSONString(map);
    }
    /**
        * @param url 请求地址
    	* @param param 请求数据 data部分格式化成JSON字符串
        * @return java.lang.String
        * @author shuaic
        * @date 2021/9/15 22:31
    */
    public TmsResponse  sendHttpRequest(String url ,String param) {
        System.out.println(param);
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        CloseableHttpResponse closeableHttpResponse = null;
        try {
           // String url = "http://tms-test.tcl.com/tms-ordercenter/dispatch/bornDispatchAndTask";
            String contractParam = createSign(param);
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", ContentType.APPLICATION_JSON.getMimeType());
            //body
            StringEntity entity = new StringEntity(contractParam , ContentType.create(ContentType.APPLICATION_FORM_URLENCODED.getMimeType(), "UTF-8"));
            httpPost.setEntity(entity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            //执行
            closeableHttpResponse = closeableHttpClient.execute(httpPost);
            int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                Shift.fatal("请求接口失败，返回状态码为："+statusCode);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        String responseString = "";
        TmsResponse tmsResponse = null;
        try {
            if (closeableHttpResponse != null) {
                responseString = EntityUtils.toString(closeableHttpResponse.getEntity(), "UTF-8");//请求tms接口
                log.info(responseString);
                tmsResponse = JSONObject.parseObject(responseString, TmsResponse.class);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
           Shift.fatal("获取返回信息失败");
        }

        return tmsResponse;

    }
}
